(function() {
  let currentAlbum = sessionStorage.getItem('currentAlbum') || 'life';

  const album_nav = document.querySelector('.album_nav');
  const navItemList = album_nav.querySelectorAll('span');
  const album_images = document.querySelector('.album_images');

  watchCurrent()

  album_nav.addEventListener('click', (e) => {
    const element = e.target;
    const id = element.id;
    if (id && id !== currentAlbum) {
      currentAlbum = id;
      sessionStorage.setItem('currentAlbum', id);

      watchCurrent()
    }
  })

  function watchCurrent() {
    for (let i = 0; i < navItemList.length; i++) {
      if (navItemList[i].id !== currentAlbum) {
        navItemList[i].className = 'album_nav-Item';
      } else {
        navItemList[i].className = 'album_nav-Item current_nav';
      }
    }

    const keyWord = `image_${currentAlbum}Json`;
    const imageJson = window[keyWord];

    refreshAlbum(imageJson)
  }

  function refreshAlbum(imageJson) {
    const firstLine = document.querySelector('.album_imgBox-first');
    const secondLine = document.querySelector('.album_imgBox-second');
    const thirdLine = document.querySelector('.album_imgBox-third');
    const fourLine = document.querySelector('.album_imgBox-four');

    if (!imageJson) {
      firstLine.innerHTML = '';
      secondLine.innerHTML = '';
      thirdLine.innerHTML = '';
      fourLine.innerHTML = '';
      album_images.className = 'album_images nothingImage';
      return
    }
    else album_images.className = 'album_images';
    const length = imageJson.length;

    let firstString = '', 
    secondString = '',
    thirdString = '',
    fourString = '';

    for (let i = length - 1; i >= 0; i--) {
      let li = `<li>`;
      const msgBox = `<div class="album_img-msg">
        <p>
          摘要：<span>${imageJson[i].message}</span>
        </p>
        <p>
          时间：<span>${imageJson[i].time}</span>
        </p>
      </div>`;

      li += `<img class="album_img" src="/photoAlbum/image/${imageJson[i].name}" title="${imageJson[i].message}" alt="${imageJson[i].message}">`;
      li += msgBox
      li += '</li>'

      if ((i + 4) % 4 === 0) {
        firstString += li
      }
      else if ((i + 3) % 4 === 0) {
        secondString += li
      }
      else if ((i + 2) % 4 === 0) {
        thirdString += li
      }
      else if ((i + 1) % 4 === 0) {
        fourString += li
      }
    }

    firstLine.innerHTML = firstString;
    secondLine.innerHTML = secondString;
    thirdLine.innerHTML = thirdString;
    fourLine.innerHTML = fourString;
  }
  
})()